import requests
import pymysql
import threading

def download_img(img_url, target_img_path,semaphore):
    print(img_url)
    semaphore.acquire()
    #header = {"Authorization": "Bearer " + api_token}  # 设置http header，视情况加需要的条目，这里的token是用来鉴权的一种方式
    r = requests.get(img_url, stream=True)
    print(r.status_code)  # 返回状态码
    if r.status_code == 200:
        open(target_img_path, 'wb').write(r.content)  # 将内容写入图片
        print("done")
        semaphore.release()  # 释放
    del r



class MyDbError(Exception):
    def __str__(self):
        return '数据库连接错误'


class MyDb(object):
    def __init__(self, host, user, passwd, db, port=32000, charset='utf8'):
        try:
            self.conn = pymysql.connect(
                host=host, user=user, passwd=passwd, db=db,
                port=port, charset=charset
            )
        except Exception as e:
            raise MyDbError
            print("连接数据库异常当前连接host:%s,user:%s,passwd:%s,port:%s,db:%s" % (host, user, passwd, port, db))
        else:
            self.cur = self.conn.cursor(cursor=pymysql.cursors.DictCursor)
            print("成功连接数据库")

    def query(self, sql):
        try:
            res = self.cur.execute(sql)
        except Exception as e:
            return e
            print("查询sql异常，请检查sql" + str(e))
        return self.cur.fetchall()

    def other(self, sql):
        try:
            self.cur.execute(sql)
        except Exception as e:
            return e
        self.conn.commit()
        return self.cur.rowcount
        # 如果sql执行成功，返回影响的函数

    def __del__(self):
        self.cur.close()
        self.conn.close()




if __name__ == '__main__':
    # 1.连接数据库，
    # 2.查询档案数据，放入字典中
    # 3.循环字典，下载图片

    #数据库地址
    host = "192.168.13.63"
    # 数据库用户名
    user = "root"
    # 数据库密码
    passwd = "introcks1234"
    # 数据库名称
    db = "ifaas_community_sec"
    mydb = MyDb(host,user,passwd,db)
    #服务器url前缀
    prefix_image_url ="http://"+host+":8080"
    #下载根路径
    prefix_image_path = "/Users/liuwei/Documents/tmp/img/"

    # 查询数据
    nonLocalSql = "select small_image,plate_number from t_vehicle_archives_info limit 10"
    #ths = []
    semaphore = threading.BoundedSemaphore(16)  # 最多允许16个线程同时运行
    for item in mydb.query(nonLocalSql):
        imageUrl = prefix_image_url+item["small_image"]
        imagePath = prefix_image_path+item["plate_number"]+".jpg"
        download_img(imageUrl, imagePath)
        t = threading.Thread(target=download_img, args=(imageUrl,imagePath,semaphore))
        # 调用getImg函数，把每个分页的url传进去
        #ths.append(t)
        t.start()
    #for t in ths:
     #   t.join()  # 这个是为了主线程等待子线程执行结束



